// composables/useHttp.ts
import { $fetch } from 'ofetch';
import { useRuntimeConfig } from '#app';
import { ElMessage } from 'element-plus';

interface RequestOptions {
    customBaseURL?: string;
    [key: string]: any;
}

type HttpMethod = 'GET' | 'POST' | 'PUT' | 'DELETE';

// 请求拦截器
function handleRequest(options: RequestOptions) {
    options.headers = {
        ...options.headers,
        'Content-Type': 'application/json',
    };

    // 添加基础 URL
    const config = useRuntimeConfig();
    options.baseURL = options.customBaseURL || config.public.apiBase;

    // 添加请求头，例如认证信息
    // const userStore = useUserStore(); // 假设你有一个用户存储
    // if (userStore.isLogin) {
    //     options.headers.Authorization = `Bearer ${userStore.getToken}`;
    // }
}

// 响应拦截器
function handleResponse(response: any) {
    if (response.error) {
        throw new Error(response.error.message);
    }

    // 处理特定状态码
    const handleStatus = (status: number) => {
        switch (status) {
            case 401:
                ElMessage.error('未授权');
                navigateTo('/login');
                break;
            case 403:
                ElMessage.error('禁止访问');
                break;
            case 404:
                ElMessage.error('资源未找到');
                break;
            case 500:
                ElMessage.error('服务器内部错误');
                break;
            default:
                ElMessage.error('未知错误');
        }
    };

    if (response.status >= 400) {
        handleStatus(response.status);
        throw new Error(response.statusText);
    }

    return response._data;
}

// 封装 $fetch
const fetch = $fetch.create({
    onRequest: handleRequest,
    onResponse: handleResponse,
    onResponseError: ({ response }) => {
        ElMessage.error('请求失败');
        throw new Error(response.statusText);
    },
});

// 导出封装后的请求方法
export const useHttp = {
    get: <T>(url: string, params?: any) => {
        return fetch<T>(url, { method: 'GET', params });
    },
    post: <T>(url: string, body?: any) => {
        return fetch<T>(url, { method: 'POST', body });
    },
    put: <T>(url: string, body?: any) => {
        return fetch<T>(url, { method: 'PUT', body });
    },
    delete: <T>(url: string, body?: any) => {
        return fetch<T>(url, { method: 'DELETE', body });
    },
};